package net.csdn.business.discuss.api.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.discuss.api.enums.DiscussActionEventEnum;
import net.csdn.business.discuss.api.mapper.DiscussCommentMapper;
import net.csdn.business.discuss.api.mapper.DiscussMapper;
import net.csdn.business.discuss.api.model.dto.*;
import net.csdn.business.discuss.api.model.entity.Discuss;
import net.csdn.business.discuss.api.model.entity.DiscussComment;
import net.csdn.business.discuss.api.model.query.BatchLikeRecordQuery;
import net.csdn.business.discuss.api.model.query.DiscussCommentQuery;
import net.csdn.business.discuss.api.model.vo.DiscussCategoryVO;
import net.csdn.business.discuss.api.model.vo.DiscussCommentVO;
import net.csdn.business.discuss.api.model.vo.DiscussSectionVO;
import net.csdn.business.discuss.api.model.vo.DiscussVO;
import net.csdn.business.discuss.api.service.*;
import net.csdn.business.discuss.common.config.AsyncThreadPoolConfig;
import net.csdn.business.discuss.common.constant.RedisConstants;
import net.csdn.business.discuss.common.enums.ResultCodeEnum;
import net.csdn.business.discuss.common.exception.BusinessException;
import net.csdn.business.discuss.common.model.vo.UserInfoVO;
import net.csdn.business.discuss.feign.api.UserFeignClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;


/**
 * @ClassName DiscussCommentServiceImpl
 * @Description 讨论评论Service业务层处理
 * @Author zhangyl
 * @Date 2023/7/18 11:23
 */
@Slf4j
@Service
public class DiscussCommentServiceImpl extends ServiceImpl<DiscussCommentMapper, DiscussComment> implements IDiscussCommentService
{

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private IDiscussIdService discussIdService;

    @Autowired
    @Lazy
    private IDiscussService discussService;

    @Autowired
    private IDiscussCategoryService discussCategoryService;

    @Autowired
    private IDiscussActivityService discussActivityService;

    @Autowired
    private IDiscussAnswerRecordService discussAnswerRecordService;

    @Autowired
    private IDiscussLikeService discussLikeService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private DiscussMapper discussMapper;

    @Resource(name=AsyncThreadPoolConfig.ASYNC_EXECUTOR_POOL_NAME)
    private ThreadPoolTaskExecutor asyncExecutor;

    /**
     * 分页查询讨论评论列表
     *
     * @param query 讨论评论
     * @return 讨论评论
     */
    @Override
    public Page<DiscussCommentVO> findPageList(DiscussCommentQuery query) throws Exception{
        //获得Page对象
        String currUserId=query.getCurrUserId();
        Page<DiscussCommentVO> page = query.getPage();
        List<DiscussCommentVO> pageList=baseMapper.findPageList(page,query);
        if(pageList!=null&&pageList.size()>0){
            List<String> userIds=new ArrayList<>();
            List<String> discussIds=new ArrayList<>();
            pageList.stream().forEach(commentVO->{
                String createBy=commentVO.getCreatedBy();
                userIds.add(createBy);
                String discussId=commentVO.getObjectId();
                discussIds.add(discussId);
            });
            Future<List<String>> taskA =asyncExecutor.submit(()->{
                //批量查询用户点赞列表
                List<String> likeRecords=new ArrayList<>();
                if(StringUtils.isNotBlank(currUserId)){
                    BatchLikeRecordQuery params=new BatchLikeRecordQuery();
                    params.setTargetType(2);
                    params.setUserId(query.getCurrUserId());
                    params.setTargetIds(discussIds);
                    likeRecords=discussLikeService.selectLikeRecordBatch(params);
                }
                return likeRecords;
            });
            Future<Map<String, UserInfoVO>> taskB =asyncExecutor.submit(()->{
                //批量查询用户信息
                Map<String, UserInfoVO> userInfoMap=new HashMap<>();
                try {
                    userInfoMap=userFeignClient.batchQuery(userIds);
                }catch (Exception e){
                    log.info("query remote user info error");
                }
                return userInfoMap;
            });
            List<String> finalLikeRecords = taskA.get();
            Map<String, UserInfoVO> finalUserInfoMap = taskB.get();
            pageList.stream().parallel().forEach(discussVO->{
                String discussId=discussVO.getObjectId();
                String createBy=discussVO.getCreatedBy();
                UserInfoVO userInfoVo =finalUserInfoMap.get(createBy);
                if(userInfoVo!=null){
                    discussVO.setCreatedByUserName(userInfoVo.getUsername());
                    discussVO.setCreatedByUserPhoto(userInfoVo.getPhoto());
                }
                if(StringUtils.isNotBlank(currUserId)&& finalLikeRecords.contains(discussId)){
                    discussVO.setIsLike(true);
                }
            });
        }
        page.setRecords(pageList);
        return page;
    }

    @Override
    public Page<DiscussCommentVO> findReplyPageList(DiscussCommentQuery query) throws Exception{
        //获得Page对象
        String currUserId=query.getCurrUserId();
        Page<DiscussCommentVO> page = query.getPage();
        List<DiscussCommentVO> pageList=baseMapper.findReplyPageList(page,query);
        if(pageList!=null&&pageList.size()>0){
            List<String> userIds=new ArrayList<>();
            List<String> discussIds=new ArrayList<>();
            pageList.stream().forEach(commentVO->{
                String createBy=commentVO.getCreatedBy();
                userIds.add(createBy);
                String discussId=commentVO.getObjectId();
                discussIds.add(discussId);
            });
            Future<List<String>> taskA =asyncExecutor.submit(()->{
                //批量查询用户点赞列表
                List<String> likeRecords=new ArrayList<>();
                if(StringUtils.isNotBlank(currUserId)){
                    BatchLikeRecordQuery params=new BatchLikeRecordQuery();
                    params.setTargetType(3);
                    params.setUserId(query.getCurrUserId());
                    params.setTargetIds(discussIds);
                    likeRecords=discussLikeService.selectLikeRecordBatch(params);
                }
                return likeRecords;
            });
            Future<Map<String, UserInfoVO>> taskB =asyncExecutor.submit(()->{
                //批量查询用户信息
                Map<String, UserInfoVO> userInfoMap=new HashMap<>();
                try {
                    userInfoMap=userFeignClient.batchQuery(userIds);
                }catch (Exception e){
                    log.info("query remote user info error");
                }
                return userInfoMap;
            });
            List<String> finalLikeRecords = taskA.get();
            Map<String, UserInfoVO> finalUserInfoMap = taskB.get();
            pageList.stream().parallel().forEach(discussVO->{
                String discussId=discussVO.getObjectId();
                String createBy=discussVO.getCreatedBy();
                UserInfoVO userInfoVo =finalUserInfoMap.get(createBy);
                if(userInfoVo!=null){
                    discussVO.setCreatedByUserName(userInfoVo.getUsername());
                    discussVO.setCreatedByUserPhoto(userInfoVo.getPhoto());
                }
                if(StringUtils.isNotBlank(currUserId)&& finalLikeRecords.contains(discussId)){
                    discussVO.setIsLike(true);
                }
            });
        }
        page.setRecords(pageList);
        return page;
    }

    /**
     * 根据id查询讨论评论
     * 
     * @param id 讨论评论主键
     * @return 讨论评论
     */
    @Override
    public DiscussCommentVO selectDiscussCommentById(String id)
    {
        return baseMapper.selectDiscussCommentById(id);
    }

    /**
     * 查询讨论评论列表
     * 
     * @param query 讨论评论
     * @return 讨论评论
     */
    @Override
    public List<DiscussCommentVO> selectDiscussCommentList(DiscussCommentQuery query)
    {
        return baseMapper.selectDiscussCommentList(query);
    }

    /**
     * 新增讨论评论
     *
     * @param params
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertDiscussComment(NewDiscussCommentDTO params)
    {
        String discussId=params.getDiscussId();
        String currUserId=params.getCurrUserId();
        DiscussComment discussComment=new DiscussComment();
        BeanUtils.copyProperties(params,discussComment);
        String id= IdUtil.fastSimpleUUID();
        discussComment.setObjectId(id);
        discussComment.setType(1);
        discussComment.setCreatedBy(currUserId);
        Integer serialNumber=discussIdService.getMaxId(discussId,2);
        discussComment.setSerialNumber(serialNumber);
        int result=baseMapper.insert(discussComment);
        //修改discuss的评论数量
        if(result>0){
            discussService.updateCommentTotal(discussId,1);
            //清除讨论列表缓存
            String sourceId=params.getSourceId();
            if(StringUtils.isNotBlank(sourceId)){
                StringBuilder cacheName = new StringBuilder(RedisConstants.DISCUSS_LIST_PAGE);
                cacheName.append(sourceId);
                Cache cache=null;
                try{
                    cache = cacheManager.getCache(cacheName.toString());
                    cache.clear();
                    StringBuilder myDiscussCacheName = new StringBuilder(RedisConstants.DISCUSS_MY_LIST_PAGE);
                    myDiscussCacheName.append(currUserId);
                    StringBuilder myJoinDiscussCacheName = new StringBuilder(RedisConstants.DISCUSS_JOIN_LIST_PAGE);
                    myJoinDiscussCacheName.append(currUserId);
                    Cache myDiscussCache = cacheManager.getCache(myDiscussCacheName.toString());
                    myDiscussCache.clear();
                    Cache myJoinDiscussCache = cacheManager.getCache(myDiscussCacheName.toString());
                    myJoinDiscussCache.clear();
                }catch (Exception e){
                    log.info("cache evict cache name:{} error: {} !",cacheName.toString(),e.getMessage());
                }
            }
        }
        return id;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer insertDiscussReply(NewDiscussReplyDTO params) {
        String parentId=params.getParentId();
        //根据parentId查询评论
        DiscussCommentVO discussCommentVO=baseMapper.selectDiscussCommentById(parentId);
        if(discussCommentVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"parentId");
        }
        String discussId=discussCommentVO.getDiscussId();
        DiscussVO discussVO=discussService.selectDiscussById(discussId);
        if(discussVO==null){
            throw new BusinessException(ResultCodeEnum.DISCUSS_NO_EXIST_ERROR);
        }
        Integer isClosed=discussVO.getIsClosed();
        if(isClosed==1){
            throw new BusinessException(ResultCodeEnum.DISCUSS_CLOSE_ERROR);
        }
        DiscussComment discussComment=new DiscussComment();
        BeanUtils.copyProperties(params,discussComment);
        String id= IdUtil.fastSimpleUUID();
        discussComment.setObjectId(id);
        discussComment.setDiscussId(discussId);
        discussComment.setType(2);
        discussComment.setCreatedBy(params.getCurrUserId());
        Integer serialNumber=discussIdService.getMaxId(parentId,3);
        discussComment.setSerialNumber(serialNumber);
        int result=baseMapper.insert(discussComment);
        //修改discuss的评论数量
        if(result>0){
            //更新discuss记录的回复数量
            discussService.updateReplyTotal(discussId,1);
            //更新discuss_comment记录的回复数量
            baseMapper.updateReplyTotal(parentId,1);
        }
        //发送评论事件
        BaseActivityDTO createActivity=new BaseActivityDTO();
        createActivity.setDiscussId(id);
        createActivity.setSourceId(discussVO.getSourceId());
        createActivity.setActionUid(params.getCurrUserId());
        createActivity.setSourceType(discussVO.getSourceType());
        DiscussActivityEventDTO eventDTO=DiscussActivityEventDTO.build(DiscussActionEventEnum.CREATE_REPLY,createActivity);
        discussActivityService.sendDiscussActivity(eventDTO);
        return result;
    }

    /**
     * 修改讨论评论
     *
     * @param params 讨论评论
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateDiscussComment(UpdateDiscussCommentDTO params)
    {
        String id=params.getId();
        String currUserId=params.getCurrUserId();
       /* DiscussCommentVO discussCommentVO=baseMapper.selectDiscussCommentById(id);
        if(discussCommentVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        String createBy=discussCommentVO.getCreatedBy();
        if(!createBy.equals(currUserId)){
            throw new BusinessException(ResultCodeEnum.UNAUTHORIZED);
        }*/
        DiscussComment discussComment=new DiscussComment();
        BeanUtils.copyProperties(params,discussComment);
        discussComment.setLastModifiedBy(currUserId);
        LambdaUpdateWrapper<DiscussComment> updateWrapper = new UpdateWrapper<DiscussComment>().lambda();
        updateWrapper.eq(DiscussComment::getObjectId, id);
        Integer result=baseMapper.update(discussComment,updateWrapper);
        if(result>0){
            //清除讨论列表缓存
            String sourceId=params.getSourceId();
            if(StringUtils.isNotBlank(sourceId)){
                StringBuilder cacheName = new StringBuilder(RedisConstants.DISCUSS_LIST_PAGE);
                cacheName.append(sourceId);
                Cache cache=null;
                try{
                    cache = cacheManager.getCache(cacheName.toString());
                    cache.clear();
                    StringBuilder myDiscussCacheName = new StringBuilder(RedisConstants.DISCUSS_MY_LIST_PAGE);
                    myDiscussCacheName.append(currUserId);
                    StringBuilder myJoinDiscussCacheName = new StringBuilder(RedisConstants.DISCUSS_JOIN_LIST_PAGE);
                    myJoinDiscussCacheName.append(currUserId);
                    Cache myDiscussCache = cacheManager.getCache(myDiscussCacheName.toString());
                    myDiscussCache.clear();
                    Cache myJoinDiscussCache = cacheManager.getCache(myDiscussCacheName.toString());
                    myJoinDiscussCache.clear();
                }catch (Exception e){
                    log.info("cache evict cache name:{} error: {} !",cacheName.toString(),e.getMessage());
                }
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateDiscussReply(UpdateDiscussReplyDTO params) {
        String id=params.getId();
        String currUserId=params.getCurrUserId();
        DiscussCommentVO discussCommentVO=baseMapper.selectDiscussCommentById(id);
        if(discussCommentVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        String createBy=discussCommentVO.getCreatedBy();
        if(!createBy.equals(currUserId)){
            throw new BusinessException(ResultCodeEnum.UNAUTHORIZED);
        }
        DiscussComment discussComment=new DiscussComment();
        BeanUtils.copyProperties(params,discussComment);
        discussComment.setLastModifiedBy(currUserId);
        LambdaUpdateWrapper<DiscussComment> updateWrapper = new UpdateWrapper<DiscussComment>().lambda();
        updateWrapper.eq(DiscussComment::getObjectId, id);
        return baseMapper.update(discussComment,updateWrapper);
    }


    /**
     * 删除讨论评论信息
     * 
     * @param params 讨论评论主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteDiscussCommentById(DeleteResourceDTO params)
    {
        String id=params.getId();
        String currUserId=params.getCurrUserId();
        DiscussCommentVO discussCommentVO=baseMapper.selectDiscussCommentById(id);
        if(discussCommentVO==null||discussCommentVO.getType()!=1){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        //判断是否被标记为采纳答案
        Integer isRemark=discussCommentVO.getIsRemark();
        String discussId=discussCommentVO.getDiscussId();
        if(isRemark==1){
            //如果此条评论被标记为答案，则取消标记
            LambdaUpdateWrapper<Discuss> updateWrapper = new UpdateWrapper<Discuss>().lambda();
            updateWrapper.eq(Discuss::getObjectId, discussId);
            updateWrapper.set(Discuss::getIsAnswered,0);
            updateWrapper.set(Discuss::getAnswerId,null);
            discussMapper.update(null,updateWrapper);
            discussAnswerRecordService.deleteAnswerRecordByDiscussId(discussId);
        }
       /* String createBy=discussCommentVO.getCreatedBy();
        if(!createBy.equals(currUserId)){
            throw new BusinessException(ResultCodeEnum.UNAUTHORIZED);
        }*/
        Integer replyCount=discussCommentVO.getReplyTotal();
        int result=0;
        if(replyCount>0){
            //如果此评论存在回复，则清空当前评论的内容，先标记删除
            LambdaUpdateWrapper<DiscussComment> updateWrapper = new UpdateWrapper<DiscussComment>().lambda();
            updateWrapper.eq(DiscussComment::getObjectId, id);
            updateWrapper.set(DiscussComment::getIsDeleted,1);
            updateWrapper.set(DiscussComment::getContent,null);
            updateWrapper.set(DiscussComment::getIsRemark,0);
            updateWrapper.set(DiscussComment::getMdContent,null);
            result=baseMapper.update(null,updateWrapper);
        }else{
            //如果没有回复项，则直接删除
            LambdaQueryWrapper<DiscussComment> queryWrapper = new LambdaQueryWrapper<DiscussComment>();
            queryWrapper.eq(DiscussComment::getObjectId, params.getId());
            result=baseMapper.delete(queryWrapper);
            if(result>0){
                discussService.updateCommentTotal(discussId,-1);
            }
        }
        //清除讨论列表缓存
        String sourceId=params.getSourceId();
        if(StringUtils.isNotBlank(sourceId)){
            StringBuilder cacheName = new StringBuilder(RedisConstants.DISCUSS_LIST_PAGE);
            cacheName.append(sourceId);
            Cache cache=null;
            try{
                cache = cacheManager.getCache(cacheName.toString());
                cache.clear();
                StringBuilder myDiscussCacheName = new StringBuilder(RedisConstants.DISCUSS_MY_LIST_PAGE);
                myDiscussCacheName.append(currUserId);
                StringBuilder myJoinDiscussCacheName = new StringBuilder(RedisConstants.DISCUSS_JOIN_LIST_PAGE);
                myJoinDiscussCacheName.append(currUserId);
                Cache myDiscussCache = cacheManager.getCache(myDiscussCacheName.toString());
                myDiscussCache.clear();
                Cache myJoinDiscussCache = cacheManager.getCache(myDiscussCacheName.toString());
                myJoinDiscussCache.clear();
            }catch (Exception e){
                log.info("cache evict cache name:{} error: {} !",cacheName.toString(),e.getMessage());
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteDiscussReplyById(DeleteResourceDTO params) {
        String id=params.getId();
        String currUserId=params.getCurrUserId();
        DiscussCommentVO discussCommentVO=baseMapper.selectDiscussCommentById(id);
        if(discussCommentVO==null||discussCommentVO.getType()!=2){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        String createBy=discussCommentVO.getCreatedBy();
        if(!createBy.equals(currUserId)){
            throw new BusinessException(ResultCodeEnum.UNAUTHORIZED);
        }
        //删除回复
        //如果没有回复项，则直接删除
        String parentId=discussCommentVO.getParentId();
        String discussId=discussCommentVO.getDiscussId();
        LambdaQueryWrapper<DiscussComment> queryWrapper = new LambdaQueryWrapper<DiscussComment>();
        queryWrapper.eq(DiscussComment::getObjectId, params.getId());
        int result=baseMapper.delete(queryWrapper);
        if(result>0){
            //更新父评论discuss_comment的回复数量
            baseMapper.updateReplyTotal(parentId,-1);
            //更新discuss的回复数量
            discussService.updateReplyTotal(discussId,-1);
        }
        //判断父级评论是否是已删除状态，如果已经删除并且回复为0，则删除父级评论
        DiscussCommentVO parentComment=baseMapper.selectDiscussCommentById(parentId);
        if(parentComment==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        Integer isDeleted=parentComment.getIsDeleted();
        Integer replyCount=parentComment.getReplyTotal();
        if(isDeleted==1&&replyCount==0){
            //删除父级评论
            LambdaQueryWrapper<DiscussComment> deleteWrapper = new LambdaQueryWrapper<DiscussComment>();
            deleteWrapper.eq(DiscussComment::getObjectId, parentComment.getObjectId());
            result=baseMapper.delete(deleteWrapper);
            if(result>0){
                //更新discuss的评论数量
                discussService.updateCommentTotal(discussId,-1);
            }
        }
        return result;
    }

    @Override
    public void deleteDiscussCommentByDiscussId(String discussId) {
        LambdaQueryWrapper<DiscussComment> queryWrapper = new LambdaQueryWrapper<DiscussComment>();
        queryWrapper.eq(DiscussComment::getDiscussId, discussId);
        baseMapper.delete(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateReplyTotal(String commentId, Integer sum) {
        return baseMapper.updateReplyTotal(commentId,sum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer remarkAnswer(RemarkAnswerDTO params) {
        String id=params.getId();
        //根据id查询评论详情
        String currUserId=params.getCurrUserId();
        DiscussCommentVO discussCommentVO=baseMapper.selectDiscussCommentById(id);
        if(discussCommentVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        Integer isDeleted=discussCommentVO.getIsDeleted();
        if(isDeleted==1){
            throw new BusinessException(ResultCodeEnum.DISCUSS_REMARK_ANSWER_ERROR);
        }
        Integer isRemark=discussCommentVO.getIsRemark();
        if(isRemark!=0){
            throw new BusinessException(ResultCodeEnum.DISCUSS_REMARK_REPATE_ERROR);
        }
        String discussId=discussCommentVO.getDiscussId();
        //根据discussId查询discuss详情信息
        DiscussVO discussVO=discussService.selectDiscussById(discussId);
        if(discussVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        //判断权限
        String sourceId=discussVO.getSourceId();
        Integer sourceType=discussVO.getSourceType();
        String categoryId=discussVO.getCategoryId();
        //查询分类的类型
        DiscussCategoryVO discussCategoryVO=discussCategoryService.selectDiscussCategoryById(categoryId);
        if(discussCategoryVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        Integer type=discussCategoryVO.getCategoryType();
        if(type!=2){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        //将此评论或回复标记为采纳的答案
        LambdaUpdateWrapper<DiscussComment> updateWrapper = new UpdateWrapper<DiscussComment>().lambda();
        updateWrapper.eq(DiscussComment::getObjectId, id);
        updateWrapper.set(DiscussComment::getIsRemark,1);
        int result=baseMapper.update(null,updateWrapper);
        //discuss更新采纳状态和采纳答案的id;
        LambdaUpdateWrapper<Discuss> discussUpdateWrapper = new UpdateWrapper<Discuss>().lambda();
        discussUpdateWrapper.eq(Discuss::getObjectId, discussId);
        discussUpdateWrapper.set(Discuss::getIsAnswered,1);
        discussUpdateWrapper.set(Discuss::getAnswerId,id);
        result=discussMapper.update(null,discussUpdateWrapper);
        //插入采纳问题记录
        NewDiscussAnswerRecordDTO answerRecordParams=new NewDiscussAnswerRecordDTO();
        answerRecordParams.setCommentId(id);
        answerRecordParams.setUserId(discussCommentVO.getCreatedBy());
        answerRecordParams.setDiscussId(discussId);
        answerRecordParams.setCurrUserId(currUserId);
        answerRecordParams.setSourceId(sourceId);
        answerRecordParams.setSourceType(sourceType);
        discussAnswerRecordService.insertDiscussAnswerRecord(answerRecordParams);
        //清除讨论列表缓存
        try{
            StringBuilder pageCacheName = new StringBuilder(RedisConstants.DISCUSS_LIST_PAGE);
            pageCacheName.append(discussVO.getSourceId());
            Cache cache = cacheManager.getCache(pageCacheName.toString());
            cache.clear();
            StringBuilder ansowerSortCacheName = new StringBuilder(RedisConstants.DISCUSS_ANSWER_SORT_30_LIST);
            Cache answerSortCache = cacheManager.getCache(ansowerSortCacheName.toString());
            String answerSortCacheKey=sourceId+'-'+sourceType;
            answerSortCache.evict(answerSortCacheKey);
            StringBuilder myDiscussCacheName = new StringBuilder(RedisConstants.DISCUSS_MY_LIST_PAGE);
            myDiscussCacheName.append(currUserId);
            StringBuilder myJoinDiscussCacheName = new StringBuilder(RedisConstants.DISCUSS_JOIN_LIST_PAGE);
            myJoinDiscussCacheName.append(currUserId);
            Cache myDiscussCache = cacheManager.getCache(myDiscussCacheName.toString());
            myDiscussCache.clear();
            Cache myJoinDiscussCache = cacheManager.getCache(myDiscussCacheName.toString());
            myJoinDiscussCache.clear();
        }catch (Exception e){
            log.info("cache evict cache error: {} !",e.getMessage());
        }
        return result;
    }

    @Override
    public Integer unRemarkAnswer(RemarkAnswerDTO params) {
        String id=params.getId();
        //根据id查询评论详情
        String currUserId=params.getCurrUserId();
        DiscussCommentVO discussCommentVO=baseMapper.selectDiscussCommentById(id);
        if(discussCommentVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        Integer isRemark=discussCommentVO.getIsRemark();
        if(isRemark!=1){
            throw new BusinessException(ResultCodeEnum.DISCUSS_REMARK_REPATE_ERROR);
        }
        String discussId=discussCommentVO.getDiscussId();
        //根据discussId查询discuss详情信息
        DiscussVO discussVO=discussService.selectDiscussById(discussId);
        if(discussVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        //判断权限
        String sourceId=discussVO.getSourceId();
        Integer sourceType=discussVO.getSourceType();
        //判断组织或项目的管理员权限
        switch (sourceType){
            case 1:
                break;
            case 2:
                break;
        }
        String categoryId=discussVO.getCategoryId();
        //查询分类的类型
        DiscussCategoryVO discussCategoryVO=discussCategoryService.selectDiscussCategoryById(categoryId);
        if(discussCategoryVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        Integer type=discussCategoryVO.getCategoryType();
        if(type!=2){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        //将此评论或回复标记为采纳的答案
        LambdaUpdateWrapper<DiscussComment> updateWrapper = new UpdateWrapper<DiscussComment>().lambda();
        updateWrapper.eq(DiscussComment::getObjectId, id);
        updateWrapper.set(DiscussComment::getIsRemark,0);
        int result=baseMapper.update(null,updateWrapper);
        //discuss更新采纳状态和采纳答案的id;
        LambdaUpdateWrapper<Discuss> discussUpdateWrapper = new UpdateWrapper<Discuss>().lambda();
        discussUpdateWrapper.eq(Discuss::getObjectId, discussId);
        discussUpdateWrapper.set(Discuss::getIsAnswered,0);
        discussUpdateWrapper.set(Discuss::getAnswerId,null);
        result=discussMapper.update(null,discussUpdateWrapper);
        //删除采纳答案记录；
        discussAnswerRecordService.deleteAnswerRecordByDiscussId(discussId);
        //清除讨论列表缓存
        try{
            StringBuilder pageCacheName = new StringBuilder(RedisConstants.DISCUSS_LIST_PAGE);
            pageCacheName.append(discussVO.getSourceId());
            Cache cache = cacheManager.getCache(pageCacheName.toString());
            cache.clear();
            StringBuilder ansowerSortCacheName = new StringBuilder(RedisConstants.DISCUSS_ANSWER_SORT_30_LIST);
            Cache answerSortCache = cacheManager.getCache(ansowerSortCacheName.toString());
            String answerSortCacheKey=sourceId+'-'+sourceType;
            answerSortCache.evict(answerSortCacheKey);
            StringBuilder myDiscussCacheName = new StringBuilder(RedisConstants.DISCUSS_MY_LIST_PAGE);
            myDiscussCacheName.append(currUserId);
            StringBuilder myJoinDiscussCacheName = new StringBuilder(RedisConstants.DISCUSS_JOIN_LIST_PAGE);
            myJoinDiscussCacheName.append(currUserId);
            Cache myDiscussCache = cacheManager.getCache(myDiscussCacheName.toString());
            myDiscussCache.clear();
            Cache myJoinDiscussCache = cacheManager.getCache(myDiscussCacheName.toString());
            myJoinDiscussCache.clear();
        }catch (Exception e){
            log.info("cache evict cache error: {} !",e.getMessage());
        }
        return result;
    }


    @Override
    public Integer updateAuditStatus(UpdateAuditStatusDTO params) {
        LambdaUpdateWrapper<DiscussComment> updateWrapper = new UpdateWrapper<DiscussComment>().lambda();
        updateWrapper.eq(DiscussComment::getObjectId, params.getId());
        updateWrapper.set(DiscussComment::getAuditStatus, params.getAuditStatus());
        int result=baseMapper.update(null,updateWrapper);
        return result;
    }

    @Override
    public Integer deleteAnswerRemark(String sourceId, Integer sourceType) {
        LambdaUpdateWrapper<DiscussComment> updateWrapper = new UpdateWrapper<DiscussComment>().lambda();
        updateWrapper.eq(DiscussComment::getSourceId, sourceId);
        updateWrapper.eq(DiscussComment::getSourceType, sourceType);
        updateWrapper.set(DiscussComment::getIsRemark, 0);
        int result=baseMapper.update(null,updateWrapper);
        return result;
    }

    @Override
    public Integer syncDelete(SyncDeleteDTO params) {
        return baseMapper.syncDelete(params);
    }
}
